<template>
	<div class="echars">
		<div ref="echartsRef" class="overhide" :style="{ minWidth: defaultWidth }"></div>
	</div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, onUnmounted, onActivated, computed } from "vue";
import Echarts from "echarts";
import type { EChartsCoreOption, ECharts } from "echarts";
import { useStore } from "@/store";
import { nsToPxPct } from "@/util";

const props = withDefaults(
	defineProps<{
		width?: number | string;
		options: EChartsCoreOption;
	}>(),
	{
		width: "100%",
	},
);

const store = useStore();

const echartsRef = ref();
let echarts: ECharts;

const defaultWidth = computed(() => nsToPxPct(props.width));

watch(
	() => store.getters["setting/collapse"],
	() => {
		setTimeout(() => {
			refresh();
		}, 400);
	},
);

watch(
	() => props.options,
	val => {
		echarts.setOption(val);
	},
	{
		deep: true,
	},
);

function refresh() {
	clear();
	resize();
	echarts.setOption(props.options);
}

function resize() {
	echarts.resize();
}

function clear() {
	echarts.clear();
}

defineExpose({
	refresh,
	resize,
	clear,
});

onActivated(() => {
	refresh();
});

onMounted(() => {
	echarts = Echarts.init(echartsRef.value);
	echarts.setOption(props.options);
	window.addEventListener("resize", resize);
});

onUnmounted(() => {
	window.removeEventListener("resize", resize);
});
</script>

<style lang="scss" scoped>
.echars {
	width: 100%;
	height: 100%;
	overflow-x: auto;
}
.echars > div {
	height: 100%;
}
</style>
